import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/Index.vue'
import Login from '../views/Login.vue'
import Detail from '../views/Detail.vue'
import Cart from '../views/Cart.vue'
import { GET_LOCAL_ITEM } from "../utils/utils.js";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      requiredAuth: true,
      title: "卡西欧首页"
    },
    children: [
      {
        path: "/",
        name: "Index",
        component: Index,
        meta: {
          title: "卡西欧首页"
        },
      },
      {
        path: "detail/:id",
        name: "Detail",
        component: Detail,
        meta: {
          title: "商品详情"
        },
      },
      {
        path: "cart",
        name: "Cart",
        component: Cart,
        meta: {
          title: "购物车"
        },
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiredAuth: true,
      title: "登录页"
    }
  },
  // 懒加载方法
  // component: () => import( '../views/About.vue')
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  let token = GET_LOCAL_ITEM("token")
  console.log(token);
  if (to.matched.some(el => el.meta.requiredAuth)) {
    if (token) {
      next()
    } else {
      next({
        path: "/login"
      })
    }
  } else {
    next()
  }
})

router.afterEach((to) => {
  console.log(to.meta.title);
  if (to.meta.title) {
    document.title = to.meta.title;
  } else {
    document.title = "CASIO"
  }
  // ...
})
export default router
